package myJs.user.mission

import myJs.Utils._

import scala.scalajs.js.Dynamic.{global => g}
import myJs.myPkg.jquery._
import myJs.tool.Tool
import myJs.tool.Tool._
import myJs.user.mission.plot._

import scala.scalajs.js
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import myJs.Implicits._
import myJs.myPkg._
import org.scalajs.dom.ext.Ajax
import scalatags.Text.all._
import myJs.myPkg.bootstrap.Bootstrap.default._
import org.scalajs.dom.{Element, document}
import shared.SharedTool

import scala.scalajs.js.JSConverters._
import scala.scalajs.js.JSON
import myJs.user.workflow.WorkflowTool
import shared.Pojo._
import upickle.default._
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._

/**
 * Created by yz on 2019/4/25
 */
@JSExportTopLevel("MissionPreprocessResult")
object MissionPreprocessResult extends WorkflowTool with MissionResult {

  val formId = "form"
  val reRunModalId = "reRunModal"

  @JSExport("init")
  def init = {
    refreshMissionInfo(getMissionId)
    refreshFileInfo(getMissionId)
    selfInit

    //    Tool.selectTab("vPlot")
    //    Tool.selectArgTab("vPlotLayout")

    //    reRunShow

  }

  override def registerEvent = {
    super.registerEvent
    $(document.body).on("click", ".myReRun", "", (y: Element) => {
      reRun
    })
  }

  def selfInit = {
    registerEvent
  }

  def getMissionId = {
    g.missionId.toString
  }

  def reRun = {
    val bv = $("#form").bv
    bv.validate()
    val valid = bv.isValid()
    if (valid) {
      $(s"#${reRunModalId}").modal("hide")
      val element = div(id := "content",
        span(id := "info", messages("running"),
          span(id := "progress", "。。。")), " ",
        img(src := "/assets/images/running2.gif", cls := "runningImage", width := 30, height := 20)
      ).render
      val layerOptions = LayerOptions.title(Tool.zhInfo).closeBtn(0).skin("layui-layer-molv").btn(js.Array())
      val index = layer.alert(element, layerOptions)
      val url = g.jsRoutes.controllers.WorkflowController.reRun().url.toString
      val formData = $(s"#form").serialize()
      Ajax.post(url = s"${
        url
      }", data = s"${
        formData
      }", headers = Map("Content-Type" -> "application/x-www-form-urlencoded")).map {
        xhr =>
          val rs = xhr.responseText.toJDJAn
          layer.close(index)
          val valid = rs("valid").toB
          if (valid) {
            refreshFileInfo(getMissionId).map { x =>
              val options = SwalOptions(
                `type` = "success",
                title = messages("success"),
                text = messages("runSuccessfully")
              )
              Swal.swal(options)
            }
          } else {
            g.swal("Error", rs.myGet("message"), "error")
          }
      }
    }
  }

}
